# coding=utf-8

import sys
import logging
from datetime import datetime
from bind_common import BindConfig
from manage_album_load import ManageAlbumLoad
from match import Match
reload(sys)
sys.setdefaultencoding("utf-8")


class BindWoker(object):
  """绑定逻辑实现类
     不处理实际逻辑。只负责调用具体实现类。相当于总控制器
  """

  def __init__(self):
    BindConfig.init_bind_config()
    self._manage_album_load = ManageAlbumLoad()
    self._match = Match(self._manage_album_load)

  def _gene_result(self, params, timestamp):
    """生成json字符串作为http返回值

    Args:
      params: 返回的信息,可能包含的信息有两个：
              error: ErrCode信息，标志本次请求返回值的类型
              ret: 本次请求具体的返回信息
      timestamp: 本次http请求的开始时间

    Returns:
      作为http返回值的json字符串
    """
    error, ret = params
    timecost = datetime.now() - timestamp
    result = {"code": error[0], "message": error[1], "timecost": str(timecost)}
    if ret:
      result["data"] = ret
    return result

  def match(self, video_str):
    """绑定匹配

    Args:
      video_str: video id

    Returns:
      作为http返回值的json字符串
    """
    timestamp = datetime.now()
    ret = self._gene_result(self._match.match_video(video_str), timestamp)
    logging.info("call match_album, video_id:%s, result:%s" % (video_str, ret))
    return ret

  def add_album(self, album_id_str):
    """添加album

    Args:
      album_id_str: album id；或为album id列表，以,分割

    Returns:
      作为http返回值的json字符串
    """
    timestamp = datetime.now()
    ret = self._gene_result(self._manage_album_load.add_album_list(album_id_str), timestamp)
    logging.info("call add_album, album_id:%s, result:%s" % (album_id_str, ret))
    return ret

  def del_album(self, album_id, video_type):
    """删除album

    Args:
      album_id: album id
      video_type: album类型。电影，电视剧，综艺等

    Returns:
      作为http返回值的json字符串
    """
    timestamp = datetime.now()
    ret = self._gene_result(self._manage_album_load.del_album(album_id, video_type), timestamp)
    logging.info("call del_album, album_id:%s, video_type:%s, result:%s" % (album_id, video_type, ret))
    return ret

  def get_album_in_memary(self, album_id, video_type):
    """得到内存中的album信息（用于debug）

    Args:
      album_id: album id
      video_type: album类型。电影，电视剧，综艺等

    Returns:
      作为http返回值的json字符串
    """
    ret = self._manage_album_load.get_album_in_memary(album_id, video_type)
    logging.info("call get_album_in_memary, album_id:%s, video_type:%s, result:%s" % (album_id, video_type, ret))
    return ret